<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Model 
{
	protected $table = 'user';
	
	private $_id;
	private $_name;
	private $_first_name;
	private $_email;
	private $_gender;
	private $_type;
	private $_active;
	private $_creation_date;
	private $_modification_date;

	public function id()
	{
		return $this->_id;
	}
	
	public function name()
	{
		return $this->_name;
	}
	
	public function firstName()
	{
		return $this->_name;
	}
	
	public function email()
	{
		return $this->_email;
	}
	
	public function gender()
	{
		return $this->_gender;
	}
	
	public function type()
	{
		return $this->_type;
	}
	
	public function isactive()
	{
		if($this->_active == 1)
			return true;
		else
			return false;
	}
	
	public function creationDate()
	{
		return $this->_name;
	}
	
	public function modificationDate()
	{
		return $this->_modification_date;
	}
	
	/* Methode permettant de récupérer un utilisateur en fonction de son ID */
	public function getUserById($id)
	{
		$query = $this->db->select('*')->from($this->table)->where('usr_id', $id)->get()->result();
		
		if(count($query) == 1)
		{
			$this->_id 					= $query[0]->usr_id;
			$this->_name 				= $query[0]->usr_name;
			$this->_first_name 			= $query[0]->usr_first_name;
			$this->_email 				= $query[0]->usr_email;
			$this->_gender 				= $query[0]->usr_gender;
			$this->_creation_date 		= $query[0]->usr_creation_date;
			$this->_modification_date 	= $query[0]->usr_modification_date;

			return array("id" => $query[0]->usr_id,
				"name" 		=> $query[0]->usr_name,
				"firstname" => $query[0]->usr_first_name,
				"email" 	=> $query[0]->usr_email,
				"gender" 	=> $query[0]->usr_gender,
				"avatar"	=> $query[0]->usr_avatar,
				"isactive" 	=> $query[0]->usr_active);
		}
	}
	
	public function getUserByEmail($email)
	{
		$query = $this->db->select('*')
						->from($this->table)
						->where('usr_email', $email)
						->get()->result();
		
		if(count($query) >= 1)
			return $query[0]->usr_id;
		else
			return false;
	}
	
	/* Methode permettant de creer un utilisateur en base */
	public function create($name, $firstname, $email, $gender, $password, $avatar)
	{
		$userId = $this->getUserByEmail($email);

		if($userId == false)
		{
			$this->db->set('usr_name',		$name)
						->set('usr_first_name', $firstname)
						->set('usr_email',		$email)
						->set('usr_gender',		$gender)
						->set('usr_avatar',		$avatar)
						->set('usr_password',	$password)
						->set('usr_modification_date', 'NOW()', false)
						->insert($this->table);
							
			return $this->db->insert_id();
		}
		else
			return $userId;
	}
	
	/* Methode permettant de supprimer un utilisateur en base */
	public function delete($id)
	{
		return $this->db->where('id', (int) $id)
				->delete($this->table);
	}
}
?>